{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fcf15dbe",
   "metadata": {},
   "source": [
    "## 知识概念\n",
    "**语音识别：speech recognition**\n",
    "- 自动语音识别：Automatic Speech Recognition，简称：ASR\n",
    "- 语音合成：Text to Speech，简称：TTS\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67a9c1da",
   "metadata": {},
   "source": [
    "### 获取token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b70b613e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.8c993524cda625372e32c91f98902911.315360000.1967464060.282335-26192069', 'expires_in': 2592000, 'session_key': '9mzdCy4tsL+4wEybNmFUNHmxSrZSO807nHTLPfrDFgD4r9jhVQlfDcQTtXTyp6bU/sflq9gPpm/bYrtPu1rgbD2HGJy+vg==', 'access_token': '24.0637834bb5933573ff34f82dab11de68.2592000.1654696060.282335-26192069', 'scope': 'audio_voice_assistant_get brain_enhanced_asr audio_tts_post brain_speech_realtime public brain_all_scope brain_asr_async wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '334577860fa87ce44bb39b7099c529db'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'6zgxEabrybKwGnwGBGKq0N4m',\n",
    "    'client_secret':'j7sb4h3CQ3iISZVCuF2wlSfztSDXVYGR'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "937c7c20",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.0637834bb5933573ff34f82dab11de68.2592000.1654696060.282335-26192069'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "token = response.json()['access_token']\n",
    "token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "42e544fe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "url is http://vop.baidu.com/server_api?cuid=123456PYTHON&token=24.0637834bb5933573ff34f82dab11de68.2592000.1654696060.282335-26192069&dev_pid=1537\n",
      "header is {'Content-Type': 'audio/wav; rate=16000', 'Content-Length': 39591}\n",
      "Request time cost 0.412295\n",
      "{\"corpus_no\":\"7095732908495333997\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"我想想。\"],\"sn\":\"545894193301652104060\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '6zgxEabrybKwGnwGBGKq0N4m'\n",
    "SECRET_KEY = 'j7sb4h3CQ3iISZVCuF2wlSfztSDXVYGR'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '普通话.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "speech_data = []\n",
    "with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "    speech_data = speech_file.read()\n",
    "length = len(speech_data)\n",
    "if length == 0:\n",
    "    raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "#测试自训练平台需要打开以下信息\n",
    "#params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "params_query = urlencode(params);\n",
    "headers = {\n",
    "    'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "    'Content-Length': length\n",
    "}\n",
    "url = ASR_URL + \"?\" + params_query\n",
    "print(\"url is\", url);\n",
    "print(\"header is\", headers)\n",
    "# print post_data\n",
    "req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "try:\n",
    "    begin = timer()\n",
    "    f = urlopen(req)\n",
    "    result_str = f.read()\n",
    "    print(\"Request time cost %f\" % (timer() - begin))\n",
    "except  URLError as err:\n",
    "    print('asr http response http code : ' + str(err.code))\n",
    "    result_str = err.read()\n",
    "if (IS_PY3):\n",
    "    result_str = str(result_str, 'utf-8')\n",
    "print(result_str)\n",
    "with open(\"result.txt\", \"w\") as of:\n",
    "    of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "481669cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "url is http://vop.baidu.com/server_api?cuid=123456PYTHON&token=24.0637834bb5933573ff34f82dab11de68.2592000.1654696060.282335-26192069&dev_pid=1837\n",
      "header is {'Content-Type': 'audio/wav; rate=16000', 'Content-Length': 158359}\n",
      "Request time cost 2.647073\n",
      "{\"corpus_no\":\"7095732908415430115\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"啊，\"],\"sn\":\"793628824201652104060\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '6zgxEabrybKwGnwGBGKq0N4m'\n",
    "SECRET_KEY = 'j7sb4h3CQ3iISZVCuF2wlSfztSDXVYGR'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '粤语.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "DEV_PID = 1837;  # 粤语\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "speech_data = []\n",
    "with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "    speech_data = speech_file.read()\n",
    "length = len(speech_data)\n",
    "if length == 0:\n",
    "    raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "#测试自训练平台需要打开以下信息\n",
    "#params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "params_query = urlencode(params);\n",
    "headers = {\n",
    "    'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "    'Content-Length': length\n",
    "}\n",
    "url = ASR_URL + \"?\" + params_query\n",
    "print(\"url is\", url);\n",
    "print(\"header is\", headers)\n",
    "# print post_data\n",
    "req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "try:\n",
    "    begin = timer()\n",
    "    f = urlopen(req)\n",
    "    result_str = f.read()\n",
    "    print(\"Request time cost %f\" % (timer() - begin))\n",
    "except  URLError as err:\n",
    "    print('asr http response http code : ' + str(err.code))\n",
    "    result_str = err.read()\n",
    "if (IS_PY3):\n",
    "    result_str = str(result_str, 'utf-8')\n",
    "print(result_str)\n",
    "with open(\"result.txt\", \"w\") as of:\n",
    "    of.write(result_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86e1a881",
   "metadata": {},
   "source": [
    "### 真人对话机器\n",
    "- 识别语音：转换百度语音识别指定格式文件\n",
    "- 调用百度asr接口，转换文本\n",
    "- 回复，数据结构：字典{key:value} key 作为输入 input value 作为ouput"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "10cfa134",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Requirement already satisfied: pipwin in d:\\anaconda3\\lib\\site-packages (0.5.2)\n",
      "Requirement already satisfied: js2py in d:\\anaconda3\\lib\\site-packages (from pipwin) (0.71)\n",
      "Requirement already satisfied: pySmartDL>=1.3.1 in d:\\anaconda3\\lib\\site-packages (from pipwin) (1.3.4)\n",
      "Requirement already satisfied: packaging in d:\\anaconda3\\lib\\site-packages (from pipwin) (20.9)\n",
      "Requirement already satisfied: requests in d:\\anaconda3\\lib\\site-packages (from pipwin) (2.25.1)\n",
      "Requirement already satisfied: docopt in d:\\anaconda3\\lib\\site-packages (from pipwin) (0.6.2)\n",
      "Requirement already satisfied: six in d:\\anaconda3\\lib\\site-packages (from pipwin) (1.15.0)\n",
      "Requirement already satisfied: pyprind in d:\\anaconda3\\lib\\site-packages (from pipwin) (2.11.3)\n",
      "Requirement already satisfied: beautifulsoup4>=4.9.0 in d:\\anaconda3\\lib\\site-packages (from pipwin) (4.9.3)\n",
      "Requirement already satisfied: soupsieve>1.2 in d:\\anaconda3\\lib\\site-packages (from beautifulsoup4>=4.9.0->pipwin) (2.2.1)\n",
      "Requirement already satisfied: tzlocal>=1.2 in d:\\anaconda3\\lib\\site-packages (from js2py->pipwin) (4.2)\n",
      "Requirement already satisfied: pyjsparser>=2.5.1 in d:\\anaconda3\\lib\\site-packages (from js2py->pipwin) (2.7.1)\n",
      "Requirement already satisfied: pyparsing>=2.0.2 in d:\\anaconda3\\lib\\site-packages (from packaging->pipwin) (2.4.7)\n",
      "Requirement already satisfied: idna<3,>=2.5 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2.10)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (2021.10.8)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (1.26.4)\n",
      "Requirement already satisfied: chardet<5,>=3.0.2 in d:\\anaconda3\\lib\\site-packages (from requests->pipwin) (4.0.0)\n",
      "Requirement already satisfied: backports.zoneinfo in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.2.1)\n",
      "Requirement already satisfied: tzdata in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (2022.1)\n",
      "Requirement already satisfied: pytz-deprecation-shim in d:\\anaconda3\\lib\\site-packages (from tzlocal>=1.2->js2py->pipwin) (0.1.0.post0)\n"
     ]
    }
   ],
   "source": [
    "!pip install pipwin"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "77c22937",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Package `pyaudio` found in cache\n",
      "Downloading package . . .\n",
      "https://download.lfd.uci.edu/pythonlibs/x6hvwk7i/PyAudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "PyAudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "[*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 0 bytes / 111 kB @ 0 bytes/s [------------------] [0.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 6 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 6 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 5 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 8 kB / 111 kB @ 5 kB/s [#-----------------] [7.2%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 24 kB / 111 kB @ 14 kB/s [###---------------] [21.6%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 24 kB / 111 kB @ 13 kB/s [###---------------] [21.6%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 24 kB / 111 kB @ 13 kB/s [###---------------] [21.6%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 20 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 40 kB / 111 kB @ 19 kB/s [######------------] [36.0%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 56 kB / 111 kB @ 25 kB/s [#########---------] [50.4%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 56 kB / 111 kB @ 24 kB/s [#########---------] [50.4%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 72 kB / 111 kB @ 30 kB/s [###########-------] [64.8%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 72 kB / 111 kB @ 29 kB/s [###########-------] [64.8%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 88 kB / 111 kB @ 34 kB/s [##############----] [79.3%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b [*] 88 kB / 111 kB @ 33 kB/s [##############----] [79.3%, 0s left]   \b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b Processing c:\\users\\lenovo\\pipwin\\pyaudio-0.2.11-cp38-cp38-win_amd64.whl\n",
      "PyAudio is already installed with the same version as the provided wheel. Use --force-reinstall to force an installation of the wheel.\n",
      "[*] 111 kB / 111 kB @ 33 kB/s [##################] [100%, 0s left]    \n"
     ]
    }
   ],
   "source": [
    "!pipwin install PyAudio"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ed366eee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你也好呀~~~'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "answer = {\n",
    "    \"你好\": \"你也好呀~~~\",\n",
    "    \"交个朋友吧\": \"好呀~~~我最喜欢交朋友了!\",\n",
    "    \"你叫什么名字呀\": \"我是你的智能助理小爱呀，想我就来找我呀~~~\"\n",
    "}\n",
    "answer.get(\"你好\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a0c44c9a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import speech_recognition\n",
    "r = speech_recognition.Recognizer()\n",
    "\n",
    "with speech_recognition.Microphone() as source:\n",
    "    audio = r.listen(source)\n",
    "# 将数据保存到wav文件中\n",
    "with open(\"1.wav\", \"wb\") as f: \n",
    "    f.write(audio.get_wav_data(convert_rate=16000))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "bf8f2c9b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你也好呀~~~\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = '6zgxEabrybKwGnwGBGKq0N4m'\n",
    "SECRET_KEY = 'j7sb4h3CQ3iISZVCuF2wlSfztSDXVYGR'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = '1.wav'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:];  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON';\n",
    "# 采样率\n",
    "RATE = 16000;  # 固定值\n",
    "\n",
    "DEV_PID = 1537;  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "speech_data = []\n",
    "with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "    speech_data = speech_file.read()\n",
    "length = len(speech_data)\n",
    "if length == 0:\n",
    "    raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "#测试自训练平台需要打开以下信息\n",
    "#params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID, 'lm_id' : LM_ID}\n",
    "params_query = urlencode(params);\n",
    "headers = {\n",
    "    'Content-Type': 'audio/' + FORMAT + '; rate=' + str(RATE),\n",
    "    'Content-Length': length\n",
    "}\n",
    "url = ASR_URL + \"?\" + params_query\n",
    "# print(\"url is\", url);\n",
    "# print(\"header is\", headers)\n",
    "# print post_data\n",
    "req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "try:\n",
    "    begin = timer()\n",
    "    f = urlopen(req)\n",
    "    result_str = f.read()\n",
    "#     print(\"Request time cost %f\" % (timer() - begin))\n",
    "except  URLError as err:\n",
    "    print('asr http response http code : ' + str(err.code))\n",
    "    result_str = err.read()\n",
    "if (IS_PY3):\n",
    "    result_str = str(result_str, 'utf-8')\n",
    "# print(result_str)\n",
    "print(answer.get(eval(result_str)[\"result\"][0][:-1]))\n",
    "with open(\"result.txt\", \"w\") as of:\n",
    "    of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "ec10ceee",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'corpus_no': '7095733114582308723',\n",
       " 'err_msg': 'success.',\n",
       " 'err_no': 0,\n",
       " 'result': ['你好。'],\n",
       " 'sn': '879912587811652104108'}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# str 转换成 dict\n",
    "result_str = eval(result_str)\n",
    "result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "f0e4ead5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你好'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 取出文本\n",
    "txt = result_str[\"result\"][0][:-1]\n",
    "txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "1b723939",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'你也好呀~~~'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 机器回答\n",
    "answer.get(txt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b7d6a55c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
